package user

import (
	"cat-collage-backend/internal/model"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func ResetPassword(c *gin.Context, db *gorm.DB) {
	userId, _ := c.GetPostForm("userId")
	op, _ := c.GetPostForm("oPassword")
	np, _ := c.GetPostForm("nPassword")
	if userId == "" || op == "" || np == "" {
		c.JSON(400, gin.H{"error": "Please provide username and password"})
		return
	}

	user := &model.User{}

	result := db.Where("id = ?", userId).First(&user)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		c.JSON(400, gin.H{"error": "用户不存在"})
		return
	}

	if op != user.Password {
		c.JSON(400, gin.H{"error": "旧密码错误"})
		return
	}

	if len(np) < 6 {
		c.JSON(400, gin.H{"error": "Password length must be greater than 6"})
		return
	}

	result.Where("id = ?", userId).Update("password", np)
	if result.Error != nil {
		c.JSON(500, gin.H{"msg": "Error"})
		return
	}
	c.JSON(200, gin.H{"msg": "success"})
}
